//
//  PhoneUploadViewController.m
//  RENTVISITOR
//
//  Created by wonder on 2017/8/31.
//  Copyright © 2017年 UNN. All rights reserved.
//

#import "PhoneUploadViewController.h"
#import "RentVieitor.h"
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>
#import "UIImageView+WebCache.h"


@interface PhoneUploadViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate>

@end

@implementation PhoneUploadViewController {
    
    UIImageView * editView;
    
}

- (void)viewWillAppear:(BOOL)animated {
    
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.hidden = NO;
    
}


- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.title = @"上传照片";
    if (self.imgDic == nil) {
        self.imgDic = [NSMutableDictionary dictionary];

    }
    self.view.backgroundColor = BackgroundColor;
    [self creatLeftView];
    [self creatView];
}


- (void)returnPhotoBlock:(SelectPhotoBlock)block {
    
    self.selecPhotoBlock = block;
}


- (void)creatLeftView {
    
    // 自定义导航栏左侧按钮
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(0, 0, 100,15 );
    [leftBtn setImage:[UIImage imageNamed:@"箭头左"] forState:UIControlStateNormal];
    [leftBtn setTitle:@"经纪人认证" forState:UIControlStateNormal];
    leftBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [leftBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
    leftBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [leftBtn setTitleColor:[Utils colorConvertFromString:@"#333333"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    // 自定义导航栏左侧按钮
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    rightBtn.frame = CGRectMake(0, 0, 50, 20);
    [rightBtn setTitle:@"提交" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[Utils colorConvertFromString:@"#333333"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(sumbitAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
}

- (void)creatView {
    
    
    UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, KWidth, 30)];
    textLabel.text = [NSString stringWithFormat:@"你需要上传身份证正面,反面,手持身份证照片共三张"];
    textLabel.textColor = [Utils colorConvertFromString:@"#666666"];
    textLabel.font = [UIFont boldSystemFontOfSize:13];
    textLabel.textAlignment = NSTextAlignmentCenter;
    textLabel.numberOfLines = 0;
    [self.view addSubview:textLabel];
    NSArray *titleArray = @[@"(身份证正面照片)",@"(身份证反面照片)",@"(手持身份证照片)"];
    
    CGFloat heigt = 100;
    CGFloat width = heigt*362/201;
    NSArray *imgArray = [self.imgDic allValues];
    for (int i=0; i<titleArray.count; i++) {
        
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake((KWidth-width)/2, (heigt+40)*i+50, width, heigt)];
        
        if (imgArray.count == 3) {
            
            [imgView sd_setImageWithURL:[NSURL URLWithString:imgArray[i]]];
        }else {
            
            imgView.image = [UIImage imageNamed:@"上传按钮"];
        }
        
        imgView.userInteractionEnabled = YES;
        [self.view addSubview:imgView];
        imgView.tag = 100+i;
        //添加手势
        UITapGestureRecognizer * PrivateLetterTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAvatarView:)];
        PrivateLetterTap.numberOfTouchesRequired = 1; //手指数
        PrivateLetterTap.numberOfTapsRequired = 1; //tap次数
        [imgView addGestureRecognizer:PrivateLetterTap];
        
        
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, (heigt+40)*(i+1)-20+30, KWidth, 20)];
        label.text = titleArray[i];
        label.textColor = [Utils colorConvertFromString:@"#666666"];
        label.font = [UIFont boldSystemFontOfSize:11];
        label.textAlignment = NSTextAlignmentCenter;
        [self.view addSubview:label];
        
        
    }
}

- (void)uploadFile:(UIImage *)img Withkey:(NSString *)key{
    
    if (img == nil) {
        return;
    }
    NSData *fileData = UIImageJPEGRepresentation(img, 1.0f);
    NSString *fieleImageStr = [fileData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    NSDictionary *dataDic = User_listsValue;
    NSString *url = [NSString stringWithFormat:@"%@agent/upload",Main_Url];
    NSString *number = dataDic[@"number"];
    NSString *token = dataDic[@"token"];
    NSDictionary *dic = @{
                          @"number":number,
                          @"token":token,
                          @"img":fieleImageStr
                          };
    __weak __typeof(self)weakSelf = self;
    NSString *str = [ReturnSign returnSignWithDic:dic];
    NSString *md5String = [NSString stringWithFormat:@"%@%@%@",str,APPKEY_URL,url];
    
    //32位小写
    
    //    NSString *nickname = [nameText.text stringByAddingPercentEscapesUsingEncoding:
    //                          NSUTF8StringEncoding];
    
    md5String = [LCMD5Tool MD5ForLower32Bate:md5String];
    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithDictionary:dic];
    [param setObject:md5String forKey:@"sign"];
    //    [param setValue:md5String forKey:@"sign"];
    //    __weak typeof(self)WeakSelf = self;
    [AFHttpTool requestWihtUrl:url params:param success:^(id response) {
        
        if ([response[@"code"] isEqualToString:@"10000"]) {
            
            NSDictionary *dataArray = response[@"data"];
            NSString *dicKey = dataArray[@"path"];
            if (dicKey != nil) {
                
                //将图片保存至字典
                [weakSelf.imgDic setObject:dicKey forKey:key];
                editView.image = img;
            }
                       
        }else {
            
            [APPDELEGATE showPro:response[@"message"]];
        }
        
        
    } failure:^(NSError *err) {
        
        
    }];
    
    
    //    if (self.selecImgBlock != nil) {
    //        self.selecImgBlock(editView.image);
    //    }
    //    [self.navigationController popViewControllerAnimated:YES];
}



- (void)sumbitAction {
    
    
    NSArray *keyArray = [self.imgDic allKeys];
    if (keyArray.count < 3) {
        [APPDELEGATE showPro:@"请完善照片资料"];
        return;
    }
    if (self.selecPhotoBlock != nil) {
        self.selecPhotoBlock(self.imgDic);
    }
    [self.navigationController popViewControllerAnimated:YES];
    
}


//图片点击手势
- (void)tapAvatarView:(UIGestureRecognizer *)reconger {
    
    editView = (UIImageView *)[self.view viewWithTag:reconger.view.tag];
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            // 跳转到相机页面
            UIImagePickerController* imagePickerController = [[UIImagePickerController alloc] init];
            imagePickerController.delegate = self;
            //            imagePickerController.allowsEditing = NO;
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            
            [self.navigationController presentViewController:imagePickerController animated:YES completion:NULL];
        }
        
        
        
    }];
    
    
    UIAlertAction *picAlbumAction = [UIAlertAction actionWithTitle:@"从相册中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //跳转到相册
        UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            //pickerImage.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
            
        }
        pickerImage.delegate = self;
        pickerImage.allowsEditing = NO;
//        [self presentModalViewController:pickerImage animated:YES];
        [self.navigationController presentViewController:pickerImage animated:YES completion:NULL];
            
        
    }];
    
    UIAlertAction *canceAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];

    [alertVC addAction:photoAction];
    [alertVC addAction:picAlbumAction];
    [alertVC addAction:canceAction];
    [self presentViewController:alertVC animated:YES completion:NULL];
    
}

#pragma mark -- 成功获得相片还是视频后的回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    //通过UIImagePickerControllerMediaType判断返回的是照片还是视频
    NSString* type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //如果返回的type等于kUTTypeImage，代表返回的是照片,并且需要判断当前相机使用的sourcetype是拍照还是相册
    if ([type isEqualToString:(NSString*)kUTTypeImage]) {
        
        //获取照片的原图
        UIImage *original = [info objectForKey:UIImagePickerControllerOriginalImage];
    
        //将图片大小压缩
//        UIImage *samllImg = [self scaleImage:original toKb:100];
        
//        NSData  *imageData2 = UIImageJPEGRepresentation(original,0.5f);
        
//        UIImage *samllImg = [UIImage imageWithData:imageData2];
        //long length2 = [imageData2 length]/1024.0f;
        // NSLog(@"压缩后大小%ldKB",length2);

        UIImage *samllImg = [self compressImage:original newWidth:500];
        NSString *tagStr = [NSString stringWithFormat:@"%ld",editView.tag];
        [self uploadFile:samllImg Withkey:tagStr];
        
        
        
//        //如果是拍照的照片，则需要手动保存到本地，系统不会自动保存拍照成功后的照片
//        UIImageWriteToSavedPhotosAlbum(samllImg, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
//        
//        NSURL *picurl=[info objectForKey:UIImagePickerControllerReferenceURL];
    }
    //模态方式退出uiimagepickercontroller
    [picker dismissViewControllerAnimated:YES completion:NULL];
}

-(UIImage *)scaleImage:(UIImage *)image toKb:(NSInteger)kb{
    
    if (!image) {
        return image;
    }
    if (kb<1) {
        return image;
    }
    
    kb*=1024;
    
    
    
    CGFloat compression = 0.9f;
    CGFloat maxCompression = 0.1f;
    NSData *imageData = UIImageJPEGRepresentation(image, compression);
    while ([imageData length] > kb && compression > maxCompression) {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(image, compression);
    }
    NSLog(@"当前大小:%fkb",(float)[imageData length]/1024.0f);
    UIImage *compressedImage = [UIImage imageWithData:imageData];
    return compressedImage;
    
    
    
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    
    NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
    if (error) {

    }else{
        
    }
    
    
}

- (void)backAction{
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 图片压缩
-(UIImage *) imageCompressForWidthScale:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth{
    
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = defineWidth;
    CGFloat targetHeight = height / (width / targetWidth);
    CGSize size = CGSizeMake(targetWidth, targetHeight);
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    
    if(CGSizeEqualToSize(imageSize, size) == NO){
        
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if(widthFactor > heightFactor){
            scaleFactor = widthFactor;
        }
        else{
            scaleFactor = heightFactor;
        }
        scaledWidth = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        if(widthFactor > heightFactor){
            
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
            
        }else if(widthFactor < heightFactor){
            
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
    UIGraphicsBeginImageContext(size);
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    if(newImage == nil){
        
        NSLog(@"scale image fail");
    }
    UIGraphicsEndImageContext();
    return newImage;
}

/**
 *  等比缩放本图片大小
 *
 *  @param newImageWidth 缩放后图片宽度，像素为单位
 *
 *  @return self-->(image)
 */
- (UIImage *)compressImage:(UIImage *)image newWidth:(CGFloat)newImageWidth
{
    if (!image) return nil;
    float imageWidth = image.size.width;
    float imageHeight = image.size.height;
    float width = newImageWidth;
    float height = image.size.height/(image.size.width/width);
    
    float widthScale = imageWidth /width;
    float heightScale = imageHeight /height;
    
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    
    if (widthScale > heightScale) {
        [image drawInRect:CGRectMake(0, 0, imageWidth /heightScale , height)];
    }
    else {
        [image drawInRect:CGRectMake(0, 0, width , imageHeight /widthScale)];
    }
    
    // 从当前context中创建一个改变大小后的图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    
    return newImage;
    
}


@end
